<template>
    <el-form :model="form" label-width="auto" @keydown.enter.prevent="getData">
        <el-row :gutter="12">
            <el-col :span="8">
                <el-form-item label="图标标题">
                    <el-input v-model="form.questionName" placeholder="请输入图标标题" @blur="nameBlur" clearable></el-input>
                </el-form-item>
            </el-col>
        </el-row>
    </el-form>

    <div style="display: flex">
        <el-button type="primary" :disabled="!props.editInfo.id" @click="handleAddVideo">新增图标</el-button>
        <el-button type="danger" :disabled="selectIds.length === 0" @click="batchDelete">批量取消</el-button>

        <el-button type="primary" :loading="downLoading" @click="handleDownTemplate">下载模板</el-button>

        <el-upload class="upload-component" :action="excelServer" :headers="headers" :show-file-list="false"
            :on-success="handleImportSuccess" :on-error="handleImportError" :before-upload="beforeImportUpload"
            :disabled="uploadLoading" style="margin-right: 10px">
            <el-button type="primary" :loading="uploadLoading">
                图标导入
            </el-button>
        </el-upload>
        <el-button v-ripple type="primary" @click="handleSyncQuestion" :loading="syncLoading">
            <el-icon>
                <Refresh />
            </el-icon>
            同步官方分组
        </el-button>
    </div>

    <art-table :data="tableData" :loading="tableLoading" :currentPage="pageNum" :pageSize="pageSize" :total="pageTotal"
        @current-change="currentChange" @size-change="sizeChange" @selection-change="handleSelectionChange">
        <template #default>
            <el-table-column type="selection" width="55" />
            <el-table-column label="ID" prop="id" width="120" #default="scope">
                {{ scope.row.questionId != 0 ? scope.row.questionId : scope.row.id }}
            </el-table-column>
            <el-table-column label="排序" prop="sort" width="160" #default="scope">
                <span v-if="editRowSort !== scope.$index">{{ scope.row.sort }}</span>
                <el-input v-else v-model="scope.row.sort" maxlength="6" show-word-limit style="width: 110px"
                    @keydown.enter="submitSort(scope.row.id, scope.row)" />
                <i v-if="editRowSort !== scope.$index" class="iconfont-sys edit-icon"
                    @click="editRowSort = editRowSort === scope.$index ? -1 : scope.$index">&#xe65f;</i>
                <i v-else class="iconfont-sys edit-icon" @click="submitSort(scope.row.id, scope.row)">&#xe616;</i>
            </el-table-column>
            <!-- 图标内容 -->
            <el-table-column label="图标标题" prop="questionName" width="400">
                <template #default="scope">
                    <div class="title_box">
                        <div class="title_box_right">
                            <div class="bankcont_title">
                                <div class="bankcont_title_text">{{ scope.row.questionName }}</div>
                            </div>
                            <div style="clear: both"></div>
                        </div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="封面图" prop="videourl" width="300">
                <template #default="scope">
                    <!-- <div @click="handlePreview(scope.row)">
                        <el-image :src="scope.row.questionImg" class="tableimg"></el-image>
                    </div> -->
                    <div>
                        <el-image v-if="scope.row.questionImg" :src="scope.row.questionImg" class="tableimg"
                            :preview-src-list="[scope.row.questionImg]" :preview-teleported="true" fit="cover"
                            :hide-on-click-modal="true" />
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="图标描述" prop="answer" width="300" />
            <!-- 图标链接 -->
            <!-- <el-table-column #default="scope" label="状态">
                <el-switch v-model="scope.row.isPay" :active-value="1" :inactive-value="0"
                    @change="editPay(scope.row)" />
            </el-table-column> -->

            <el-table-column label="操作时间" prop="updateTime">
                <template #default="scope">
                    {{ scope.row.updateTime }}
                </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="150">
                <template #default="scope">
                    <button-table type="edit" @click="buttonMoreClick(scope.row)" />
                    <button-table type="delete" @click="handleDel(scope.row.id)" />
                </template>
            </el-table-column>
        </template>
    </art-table>

    <!-- <add-video-dialog v-if="showAddVideoDialog" :show-add-video-visible="showAddVideoDialog" :group-info="editInfo"
        :edit-info="editData" @close-dialog="closeSelectionDialog" /> -->
    <addIconDialog v-if="showAddVideoDialog" :show-add-video-visible="showAddVideoDialog" :groupId="props.editInfo.id"
        :group-info="editInfo" :edit-info="editData" @close-dialog="closeSelectionDialog" />

    <el-dialog v-model="videoDialogVisible" width="60%" :destroy-on-close="true" class="video-dialog"
        :close-on-click-modal="false">
        <template #header>
            <h2>{{ previewTitle }}</h2>
        </template>

        <template #default>
            <video v-if="videoDialogVisible" :src="previewSrc" controls autoplay style="width: 100%; height: auto" />
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import {
    getCanSelectQuestion,
    delquestionlist,
    getIconSkillExportTemplate,
    downQuestionExcel,
    putquestioncategory,
    syncGroup
} from '@/api/questionbank'
import AddVideoDialog from './AddVideoDialog.vue'
import addIconDialog from './addIconDialog.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Upload } from '@element-plus/icons-vue'

import { useUserStore } from '@/store/modules/user'
// 用户状态

const props = defineProps({
    showQuestionDetailVisible: {
        type: Boolean
    },
    editInfo: {
        type: Object,
        default: () => {
            return { id: '' }
        }
    }
})

const editRowSort = ref(-1)

console.log(props.editInfo, "editInfo===");

const userStore = useUserStore()
const { accessToken } = userStore
const excelServer = `${import.meta.env.VITE_API_URL}ds-question-group/importIconXlsx/${props.editInfo.id}`
const headers = { Authorization: `Bearer ${accessToken}`, store_id: localStorage.getItem('lty-store-id') }


const emit = defineEmits(['uploadGroup'])

const tableData = ref([])
const pageNum = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)
const tableLoading = ref(false)
const selectIds = ref<string[]>([])
const showAddVideoDialog = ref(false)
const editData = ref({})
const syncLoading = ref(false)

const videoDialogVisible = ref(false)
const uploadLoading = ref(false)
const downLoading = ref(false)
const previewSrc = ref('')
const previewTitle = ref('')

// 常量定义
const EXCEL_MIME_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
const MAX_FILE_SIZE = 50 * 1024 * 1024 // 50MB

const form = reactive({
    // questionType: '',
    questionName: ''
})

const currentChange = (val: number) => {
    pageNum.value = val
    getData()
}
const sizeChange = (val: number) => {
    pageSize.value = val
    pageNum.value = 1
    getData()
}

function handleSelectionChange(data: any[]) {
    selectIds.value = data.map((item) => item.id)
}

function batchDelete() {
    ElMessageBox.confirm('确定批量取消选择吗？', '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        let ids = selectIds.value.join(',')
        handleDelete(ids)
    })
}

function buttonMoreClick(item: any) {
    showAddVideoDialog.value = true
    editData.value = JSON.parse(JSON.stringify(item))
}

function handleDel(id: string) {
    ElMessageBox.confirm('确定删除吗？', '确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        handleDelete(id)
    })
}

const beforeImportUpload = (file: File): boolean => {
    const isExcel = file.type === EXCEL_MIME_TYPE
    const isLt50 = file.size < MAX_FILE_SIZE

    if (!isExcel) {
        ElMessage.error('只能上传Excel文件!')
        return false
    }

    if (!isLt50) {
        ElMessage.error('文件大小不能超过50MB!')
        return false
    }

    uploadLoading.value = true
    return true
}

const handleImportSuccess = (response: any) => {
    uploadLoading.value = false

    if (response.code === '00000') {
        ElMessage.success('导入成功')
        getData() // 刷新数据
    } else {
        ElMessage.error(response.msg || '导入失败')
    }
}

const handleImportError = (error: any) => {
    uploadLoading.value = false
    console.error('导入失败:', error)
    ElMessage.error('导入失败，请稍后重试')
}

function handlePreview(item: Record<string, any>) {
    videoDialogVisible.value = true
    previewSrc.value = item.videoUrl
    previewTitle.value = item.questionName
}

// async function editPay(row: any) {
//     const res = await putquestioncategory.putquestioncategoryId(row.id, {
//         isPay: row.isPay,
//         sort: row.sort,
//         answer: row.answer,
//         carIds: row.carIds,
//         questionImg: row.questionImg,
//         questionName: row.questionName,
//         videoUrl: row.videoUrl
//     })
//     if (res.code === '00000') {
//         ElMessage.success('编辑成功')
//         getData()
//     }
// }

async function handleDelete(ids: string) {
    try {
        const res = await delquestionlist.delquestionlistId(ids)
        if (res.code === '00000') {
            await getData()
            emit('uploadGroup')
            selectIds.value = []
            ElMessage.success('删除成功')
        }
    } catch (e) {
    } finally {
    }
}



async function handleDownTemplate() {
    try {
        downLoading.value = true
        const res = await getIconSkillExportTemplate({})
        if (res) {
            // 创建下载链接
            const link = document.createElement('a')
            link.href = URL.createObjectURL(res)
            link.download = '图标技巧导入模板'
            link.style.display = 'none'
            document.body.appendChild(link)
            link.click()
            ElMessage.success('下载成功')

            // 清理
            URL.revokeObjectURL(link.href)
            document.body.removeChild(link)
        }
    } catch (e) {

    } finally {
        downLoading.value = false
    }
}

// async function handleExportTemplate() {
//   const res = await importIconSkillTemplate(props.editInfo?.id,{})
//   if(res.code === '00000') {
//     getData()
//   }
// }

function handleAddVideo() {
    showAddVideoDialog.value = true
    editData.value = { id: '' }
}

function closeSelectionDialog(value: boolean) {
    showAddVideoDialog.value = false
    if (value) {
        emit('uploadGroup')
        getData()
    }
}

async function getData() {
    const obj: Record<string, any> = {
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        carIds: props.editInfo?.carIds,
        groupId: props.editInfo?.id,
        isGroup: '01'
    }

    for (const key in form) {
        const typedKey = key as keyof typeof form
        if (form[typedKey] !== '') {
            obj[typedKey] = form[typedKey]
        }
    }

    try {
        tableLoading.value = true
        const res = await getCanSelectQuestion(obj)
        if (res.code === '00000') {
            tableData.value = res.data.list
            pageTotal.value = res.data.total
        }
    } catch (e) {
    } finally {
        tableLoading.value = false
    }
}

const nameBlur = (e: any) => {
    pageNum.value = 1
    pageSize.value = 10
    getData()
}

const handleSyncQuestion = async () => {
    const res = await syncGroup({
        categoryIds: 1,
        name: '1',
        pageUrlType: '08'
    })
    if (res.code === '00000') {
        ElMessage.success('同步成功')
        emit('uploadGroup')
    }
}

const submitSort = async (id: string, ele: any) => {
    const res = await putquestioncategory.putquestioncategoryId(id, {
        sort: ele.sort,
        questionName: ele.questionName,
        answer: ele.answer,
        videoUrl: ele.videoUrl,
        isPay: ele.isPay,
        questionImg: ele.questionImg,
        carIds: ele.carIds,
        groupId: String(props.editInfo.id || '')
    })
    if (res.code === '00000') {
        ElMessage.success('修改成功')
        getData()
        editRowSort.value = -1
    }
}

onMounted(() => {
    getData()
})
</script>

<style scoped lang="scss">
.tableimg {
    width: 80px;
    height: 80px;
}

.upload-component {
    margin-left: 12px;
}

.edit-icon {
    margin-left: 4px;
    cursor: pointer;
    color: var(--el-color-primary);
}
</style>